using Godot;
using System.Threading.Tasks;

public partial class SceneTransition : CanvasLayer
{
    public static SceneTransition Instance { get; private set; }

    [Export] public AnimationPlayer Anim;
    [Export] public ColorRect ColorRect;

    public override void _Ready()
    {
        Instance = this;

        // 初始化时，先设为全黑，然后播放淡入
        ColorRect.Visible = true;
        ColorRect.Modulate = Colors.Black;

        // 延迟一帧播放，确保 Godot 渲染就绪
        CallDeferred("PlayInitialFadeIn");
    }

    private void PlayInitialFadeIn()
    {
        Anim.Play("fade_in");
    }

    // 切换到指定文件路径的场景
    public async void ChangeScene(string scenePath)
    {
        // 1. 播放变黑动画
        Anim.Play("fade_out");

        // 2. 等待动画播放完毕
        await ToSignal(Anim, AnimationPlayer.SignalName.AnimationFinished);

        // 3. 切换场景 (此时屏幕是全黑的)
        GetTree().ChangeSceneToFile(scenePath);

        // 4. 播放变亮动画
        Anim.Play("fade_in");

        // (可选) 等待淡入完成，防止玩家在淡入时操作
        // await ToSignal(Anim, AnimationPlayer.SignalName.AnimationFinished);
    }

    // 重载当前场景 (用于死亡重置)
    public async void ReloadCurrentScene()
    {
        Anim.Play("fade_out");
        await ToSignal(Anim, AnimationPlayer.SignalName.AnimationFinished);

        GetTree().ReloadCurrentScene();

        Anim.Play("fade_in");
    }
}